package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Resource(name = "orderMapper")
    OrderMapper orderMapper;

    /**
     * 每分钟处理一次支付超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processPaymentTimeoutOrders() {
        log.info("处理支付超时订单");
        Orders orders = Orders.builder()
                .orderTime(LocalDateTime.now().plusMinutes(-15))
                .status(Orders.PENDING_PAYMENT)
                .build();
        List<Orders> ordersList = orderMapper.toTaskSelOrder(orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("超时自动取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersList.forEach(order -> {
            order.setId(order.getId());
            orderMapper.update(orders);
        });
    }

    /**
     * 每天凌晨一点检查未完成订单
     */
    @Scheduled(cron = "0 0 3 * * ? ")
    public void processOutstandingOrders() {
        log.info("处理未完成订单");
        Orders orders = Orders.builder()
                .checkoutTime(LocalDateTime.now().plusMinutes(-3))
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        List<Orders> ordersList = orderMapper.toTaskSelOrder(orders);
        orders.setStatus(Orders.COMPLETED);
        ordersList.forEach(order -> {
            order.setId(order.getId());
            orderMapper.update(orders);
        });
    }


}
